<template>
  <div>
    <div class="goHome" v-if='$route.query.goHome' @click="$router.push({name:'home'})"></div>
    <div class="goHome" v-if='$route.query.goCardList'
         @click="$router.push({path:'/cardList',query:{goCenter:true}})"></div>
    <form id="imageForm">
      <!-- <div v-if="setPendingInfo.couponNo"> -->
      <div
          v-if="couponComDetail && !(couponComDetail.couponType=='present') && !(couponComDetail.couponType=='ticket')">
        <div class="coupon_dtl_coupon" @click="goCouponDetl(couponComDetail)">
          <div class="yun_price">
            <span>{{couponComDetail.valuation}}</span>芸券
          </div>
          <div class="couponDiv"
               :class="{'coupon_yellow':couponComDetail.couponType=='cash','coupon_green':couponComDetail.couponType=='rebate','coupon_blue':couponComDetail.couponType=='voucher','coupon_orange':couponComDetail.couponType=='present','coupon_purple':couponComDetail.couponType=='ticket'}">
            <div class="_num"
                 :class="{'coupon_color_y':couponComDetail.couponType=='cash','coupon_color_g':couponComDetail.couponType=='rebate','coupon_color_b':couponComDetail.couponType=='voucher','coupon_color_o':couponComDetail.couponType=='present','coupon_color_p':couponComDetail.couponType=='ticket'}">
              Coupon
            </div>
            <div class="_num_price">
              <coupon-num :num="couponComDetail.denomination"
                          :type="couponComDetail.couponType"></coupon-num>
            </div>
            <div class="coupon_type">{{couponComDetail.couponType | couponTp}}</div>
          </div>
          <div class="card_info">
            <div class="card_name">
              {{couponComDetail.couponName}}
            </div>
            <div class="coupon_info_item">
              <p class="star_con">
                <star :couponComScore="couponComDetail.comScore"></star>
              </p>
              <p class="info_pad">{{couponComDetail.comNum}}条</p>
            </div>
            <div class="clear"></div>
            <div class="coupon_info_item color_gray">
              <img v-if="$route.query.buy||couponComDetail.promAppro=='buy'" style="width: 1rem;height:1rem"
                   src="../../images/cashIcon.png"/>
              已出售 &nbsp; {{couponComDetail.soldnum}} &nbsp;&nbsp;  已使用  &nbsp;{{couponComDetail.usednum}}
            </div>
          </div>
        </div>
        <div class="do_score">
          <span class="left">产品评价</span>
          <p class="star_con2">
            <i class="icon iconfont" v-bind:class="{'icon-star':myScore>0,'icon-star1':myScore==0}"
               @click="doScore(1)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScore>1,'icon-star1':myScore<=1}"
               @click="doScore(2)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScore>2,'icon-star1':myScore<=2}"
               @click="doScore(3)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScore>3,'icon-star1':myScore<=3}"
               @click="doScore(4)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScore>4,'icon-star1':myScore<=4}"
               @click="doScore(5)"></i>
          </p>
          <span class="right">{{ remark }}</span>
        </div>
        <div class="textarea_con">
          <div class="textarea_con_tag">{{couponComCont.length >= 10 ? '' : '评论内容需要您写10字哦，加油！'}}</div>
          <textarea v-model="couponComCont" placeholder="亲，您觉得该电子券使用感觉如何？"></textarea>
        </div>
        <div class="valuation">
          <p>电子券估值：</p>
          <div class="valuation_text"><input v-model="worth" placeholder="您认为该电子券的芸券值（50-100之间）"
                                             @keypress="keyPress($event)" type="number"></div>
        </div>
      </div>
      <!-- 商户评论-->
      <!-- <div v-if="!setPendingInfo.couponNo"> -->
      <div>
        <div class="pendingMert" @click="mchtDetail(shopComDetail.mchtId)">
          <div class="pendingImg"><img :src="img"></div>
          <div class=pendingTit>{{shopComDetail.mchtName}}</div>
          <div class="pendingTit2 pendingMt">{{mchtType}}<span
              class="pad_l pdl5">{{shopComDetail.mchtArea}}</span></div>
        </div>

        <div class="do_score">
          <span class="left" style="left: -3.3rem;">商户评价</span>
          <p class="star_con2" style="left: -3.3rem;position: relative;">
            <i class="icon iconfont" v-bind:class="{'icon-star':myScoreShop>0,'icon-star1':myScoreShop==0}"
               @click="doScoreShop(1)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScoreShop>1,'icon-star1':myScoreShop<=1}"
               @click="doScoreShop(2)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScoreShop>2,'icon-star1':myScoreShop<=2}"
               @click="doScoreShop(3)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScoreShop>3,'icon-star1':myScoreShop<=3}"
               @click="doScoreShop(4)"></i>
            <i class="icon iconfont" v-bind:class="{'icon-star':myScoreShop>4,'icon-star1':myScoreShop<=4}"
               @click="doScoreShop(5)"></i>
          </p>
          <span class="right">{{ remarkShop }}</span>
        </div>
        <div class="textarea_con">
          <div class="textarea_con_tag">{{shopComCont.length >= 10 ? '' : '评论内容需要您写10字哦，加油！'}}</div>
          <textarea v-model="shopComCont" placeholder="亲，您觉得商家如何，服务还满意吗，周边环境感觉如何？"></textarea>
        </div>
        <div class="whiteBg">
          <div class="uploadImg">
            <ul class="uploadList">
              <li v-for="(item, index) in imagesArray" @click="previewImage(item)">
                <img :src="item">
                <span @click="removeImg($event,index)"><i class="iconfont icon-shanchu"></i></span>
              </li>
              <li class="uploadImgBtn" @click="openAlbum" v-show="imagesArray.length < 6">
                <svg aria-hidden="true" class="icon">
                  <use xmlns:xlink="http://www.w3.org/1999/xlink"
                       xlink:href="#icon-shangchuanzhaopian-"></use>
                </svg>
              </li>
            </ul>
          </div>
        </div>
        <div class="valuation">
          <p>人均：￥</p>
          <div class="valuation_text"><input maxlength="3" v-model="per" placeholder="请输入您的人均消费"
                                             @keypress="keyPress($event)" type="number"/></div>
        </div>
      </div>
      <div class="botSpace"></div>
      <div class="exchangeBtn">
        <p class="subBtn" @click="cancel">取消</p>
        <p class="mainBtn" @click="doCommentC()">发表</p>
      </div>
    </form>

  </div>
</template>
<script>
  import star from '../../componentes/global/star.vue'
  import couponNum from '../../componentes/global/couponNum.vue'
  import * as types from '../../vuex/types.js'
  import getData from '../../service/getData.js'
  import getData2 from '../../service/getData2.js'
  import {mapState} from 'vuex'
  import {Toast, Indicator} from 'mint-ui'
  import {Storage} from 'src/utils/storage.js'

  var formData = new FormData();
  export default {
    data: function () {
      return {
        myScore: 5,
        myScoreShop: 5,
        couponComDetail: '',
        shopComDetail: '',
        couponComCont: '',
        shopComCont: '',
        images: [],
        worth: '',
        per: '',
        imagesArray: [],
        mchtType: '',
        imgCount: 6,
        img:''
      }
    },
    created: async function () {
      this.showComment();
    },
    computed: {
      ...mapState({
        setPendingInfo: state => state.info.setPendingInfo,
        userInfo: state => state.user.userInfo
      }),
      remark: function () {
        if (this.myScore == 1 || this.myScore == 2) {
          return '不满意'
        } else if (this.myScore == 3) {
          return '一般'
        } else if (this.myScore == 4 || this.myScore == 5) {
          return '非常好'
        }
      },
      remarkShop: function () {
        if (this.myScoreShop == 1 || this.myScoreShop == 2) {
          return '不满意'
        } else if (this.myScoreShop == 3) {
          return '一般'
        } else if (this.myScoreShop == 4 || this.myScoreShop == 5) {
          return '非常好'
        }
      }
    },
    components: {
      star,
      couponNum
    },
    beforeRouteLeave(to, from, next) {
      if (window.isBack) {
        window.isBack = false
        this.$router.push({path: "/home"})
      }
      next()
    },
    methods: {
      //只能输入数字，禁止输入点
      keyPress() {
        let keyCode = event.keyCode;
        if (keyCode >= 48 && keyCode <= 57) {
          event.returnValue = true;
        } else {
          event.returnValue = false;
        }
      },
      showComment: function () {
        var that = this;
        getData2.showComment({'method': 'post'}, that.$route.query.mchtId, that.$route.query.couponNos).then(rep => {
          if (rep.respCode == '00') {
            this.shopComDetail = rep.content.mcht;
            this.img=rep.content.mchtLogUrl
            this.mchtType = rep.content.mchtTypeValue;
            this.couponComDetail = rep.content.coupon;
          } else {
            Toast({
              message: rep.errorInfo,
              duration: 1000
            });
          }
        })
      },
      goCouponDetl(params) {
        Storage.set("couponInfo", params);
        this.$router.push({
          name: 'couDetail',
          query: {
            type: 'noExchange',
            couponId: params.couponId,
            mchtId: params.mchtId,
            seq: params.seqNo || '',
            usrId: params.usrId || '',
            usrPicId: ''
          }
        });
      },
      mchtDetail(mchtId) {
        this.$router.push({
          name: 'merchDetail',
          query: {mchtId}
        });
      },
      doScore: function (num) {
        this.myScore = num
      },
      doScoreShop: function (num) {
        this.myScoreShop = num
      },
      cancel: function () {
        window.history.back(-1);
      },
      doCommentC: function () {
        let me = this;
        if ((me.couponComCont.trim() == '' && me.couponComDetail && me.couponComDetail.couponType != 'present' && me.couponComDetail.couponType != 'ticket') || me.shopComCont.trim() == '') {
          Toast({
            message: '评论不能为空',
            duration: 1000
          });
          return false;
        }
        ;
        if (me.couponComCont != '' && me.couponComCont.length < 10) {
          Toast({
            message: '评论不能小于10字',
            duration: 1000
          });
          return false;
        }
        ;
        if (me.shopComCont != '' && me.shopComCont.length < 10) {
          Toast({
            message: '评论不能小于10字',
            duration: 1000
          });
          return false;
        }
        ;
        if (me.myScore == '' || me.myScoreShop == '') {
          Toast({
            message: '请评分',
            duration: 1000
          });
          return false;
        }
        ;
        // if(me.worth !=''){
        // if (me.worth.length<=50 && me.worth.length>=100) {
        //     Toast({
        //         message: '50-100之间',
        //         duration: 1000
        //     });
        //     return false;
        // }
        // };

        if (me.couponComCont == '') {
          me.couponComCont == me.shopComCont
        } else if (me.shopComCont == '') {
          me.shopComCont == me.couponComCont
        }
        if (!me.couponComDetail || me.couponComDetail.couponType == 'present' || me.couponComDetail.couponType == 'ticket') {
          if (me.per == '') {
            Toast({
              message: '请填写人均',
              duration: 1000
            });
            return false;
          }
          ;
          if (me.per.length > 3) {
            Toast({
              message: '人均最多3位',
              duration: 1000
            });
            return false;
          }
          ;
          formData.append("mchtComment.mchtId", me.shopComDetail.mchtId)
          formData.append("mchtComment.per", me.per)
          formData.append("mchtComment.upCommId", 0)
          formData.append("mchtComment.dsc", Base64.encode(me.shopComCont))
          formData.append("mchtComment.replyId", 0)
          formData.append("mchtComment.commStar", me.myScoreShop)
          formData.append("mchtComment.orderId", me.$route.query.orderId)
        } else if (me.couponComDetail && me.couponComDetail.couponType != 'present' && me.couponComDetail.couponType != 'ticket') {
          if (me.worth == '') {
            Toast({
              message: '请填写电子券估值',
              duration: 1000
            });
            return false;
          }
          ;
          if (me.worth < 50 || me.worth > 100) {
            Toast({
              message: '电子券估值50-100之间',
              duration: 1000
            });
            return false;
          }
          if (me.per == '') {
            Toast({
              message: '请填写人均',
              duration: 1000
            });
            return false;
          }
          ;
          if (me.per.length > 3) {
            Toast({
              message: '人均最多3位',
              duration: 1000
            });
            return false;
          }
          ;
          console.log(me.shopComDetail.mchtId)
          formData.append("couponComment.couponId", me.couponComDetail.couponId)
          formData.append("couponComment.mchtId", me.couponComDetail.mchtId)
          formData.append("couponComment.upCommId", 0)
          formData.append("couponComment.dsc", Base64.encode(String(me.couponComCont)))
          formData.append("couponComment.replyId", 0)
          formData.append("couponComment.worth", parseInt(me.worth))
          formData.append("couponComment.commStar", me.myScore)
          formData.append("couponComment.orderId", me.$route.query.orderId)
          formData.append("mchtComment.mchtId", me.shopComDetail.mchtId)
          formData.append("mchtComment.per", me.per)
          formData.append("mchtComment.upCommId", 0)
          formData.append("mchtComment.dsc", Base64.encode(String(me.shopComCont)))
          formData.append("mchtComment.replyId", 0)
          formData.append("mchtComment.commStar", me.myScoreShop)
          formData.append("mchtComment.orderId", me.$route.query.orderId)
        }

        // Indicator.open('加载中...');
        me.$store.commit('changeState', true)
        getData.doComment({
          'method': 'post',
          headers: {'Content-Type': 'multipart/form-data'},
          data: formData
        }, me.userInfo.usrId, me.$route.query.orderId).then(rep => {
          formData = new FormData();
          if (rep.respCode == '00') {
            Toast({
              message: '评论成功',
              duration: 800
            });
            setTimeout(function () {
              if (me.$route.query.goCardList) {
                me.$router.push({path: '/cardList', query: {goCenter: true}});
              } else if (!me.$route.query.goHome && !me.$route.query.goCardList) {
                window.history.back(-1);
              } else {
                me.$router.push({name: 'home'});
              }
            }, 800)

          } else {
            Toast({
              message: rep.errorInfo,
              duration: 800
            });
          }
        })
      },

      createImage: function (file) {
        var vm = this
        var reader = null
        var leng = file.length
        for (var i = 0; i < leng; i++) {
          reader = new window.FileReader()
          reader.readAsDataURL(file[i])
          reader.onload = function (e) {
            vm.images.push(e.target.result)
          }
        }
      },
      deleteImage: function (e) {
        this.images.splice(e, 1);
        // this.images1.splice(e,1);

      },
      removeImg: function (e, index) {
        event.stopPropagation()
        this.imagesArray.splice(index, 1);
        this.imgCount++;
      },
      //打开相机
      openAlbum: function () {

        let me = this;
        wx.chooseImage({
          count: me.imgCount, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
            let localIds = res.localIds; // 返回选定照片的本地ID列表，localId可以作为img标签的src属性显示图片
            // 上传图片不能超过五个
            let localIdsLen = localIds.length
            me.imgCount = me.imgCount - localIdsLen
            me.imagesArray = me.imagesArray.concat(localIds);
            me.uploadImg(localIds)
          },
        });
      },
      //图片上传到服务器
      uploadImg: function (imgIds) {
        let me = this;
        var imgArray = imgIds, mediaIds = [], count = 0;
        upLoad();

        function upLoad() {
          if (count == imgArray.length) {
            formData.append("mediaId", mediaIds.join("+"));
            return;
          }

          wx.uploadImage({
            localId: imgArray[count].toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips: 1, // 默认为1，显示进度提示
            success: function (res) {
              mediaIds.push(res.serverId)// 返回图片的服务器端ID
              count++;
              upLoad();
            },
          });
        }


      },
      previewImage: function (item) {
        let me = this;
        wx.previewImage({
          current: item, // 当前显示图片的http链接
          urls: me.imagesArray // 需要预览的图片http链接列表
        });
      },
    }
  }
</script>
<style scoped>
  .coupon_dtl_coupon {
    margin: 0;
  }
</style>
<style>
  .pendingCmtList {
    overflow: hidden;
  }

  .goHome {
    width: 6rem;
    height: 4rem;
    z-index: 55;
    position: absolute;
    left: 0;
    top: 0;
  }

  .pendingCmtList li .li_item {
    padding: .667rem .667rem 0;
    background: #fff;
    overflow: hidden;
    margin-bottom: .6rem;
  }

  .pendingMert {
    background: #f8f8f8;

    padding: .6rem;
    height: 4rem;
  }

  .pendingImg {
    width: 3.5rem;
    height: 3.5rem;
    float: left;
  }

  .pendingImg img {
    width: 100%;
    height: 100%;
  }

  .pendingTit {
    padding-left: .6rem;
    overflow: hidden;
    line-height: 1.4rem;
  }

  .pendingTit span {
    float: right;
    font-size: 1rem;
    color: #666;
  }

  .pendingTit2 {
    padding-left: .6rem;
    overflow: hidden;
    font-size: 1rem;
    color: #666;
    line-height: 1.4rem;
  }

  .pendingCmtList .card_img {
    margin-top: 0;
  }

  .pendingMt {
    margin-top: .6rem;
  }

  .pendingBtn {
    height: 3rem;
    line-height: 3rem;
    border-top: 1px solid #e6e6e6;
    padding: 0 0 0 .667rem;
    color: #666;
  }

  .pendingBtn p {
    float: right;
    color: #fff;
    background: linear-gradient(35deg, #ec4e8a, #f95a7c);
    height: 2.2rem;
    margin-top: .4rem;
    line-height: 2.2rem;
    padding: 0 1.6rem;
    border-radius: .2rem;
  }

  .pendingCmtList .pendingTit {
    padding: 0.6rem 0 0.25rem 0.6rem
  }

  .pendingCmtList .pendingTit2 {
    padding: 0.15rem 0 0.15rem 0.6rem;
  }

  .pendingCmtList .coupon_item {
    padding-bottom: 0.5rem;
  }

  .li_item .pendingMert .pendingTit {
    padding-top: 0.3rem
  }

  .li_item .pendingMt {
    margin-top: 0
  }

  .li_item .comt_mcht_name {
    font-weight: bold;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    display: block;
    color: #333;
  }
</style>
